//index.js
//获取应用实例
var wxpay = require('../../utils/pay.js');
var util = require('../../utils/util.js');
var app = getApp();

Page({
  data: {
    mallName: wx.getStorageSync('mallName'),
    selList: '',
    confirmOrder: {},
    curAddressData: null,//收货地址
    allCoupon: [],//所有能用的优惠券
    curCoupon: null,//当前优惠券
    hasPay: false,
    storeid: app.globalData.storeId,
    cash: 0,
    choosecash: 2,
    selectImg: "/images/nav/off.png",
    showAdress: true
  },

  //选择取货方式
  selectType: function (e) {
    let Img = this.data.selectImg;
    let showAdress = this.data.showAdress;
    if (Img == "/images/nav/off.png") {
      Img = "/images/nav/on.png";
      showAdress = false;
    } else {
      Img = "/images/nav/off.png"
      showAdress = true;
    }
    this.setData({
      selectImg: Img,
      showAdress: showAdress
    })
    this.confirmOrder()
  },

  //是否选择余额支付
  chooseCashPay: function () {
    var choosecash = this.data.choosecash
    if (choosecash == 1) {
      choosecash = 2
    }
    else {
      choosecash = 1
    }
    this.setData({
      choosecash: choosecash
    })
  },
  //获取账户余额
  getUserCash: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/UserCash/GetUserCash?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            cash: res.data.Data.Cash
          })
        }
      }
    })
  },
  onShow: function (e) {
    this.initShippingAddress();
    var c = wx.getStorageSync(this.data.selList);
    if (c) {
      this.setData({
        curCoupon: c
      })
      wx.clearStorageSync(this.data.selList);
    }
    this.getUserCash()
  },
  onLoad: function (e) {
    var that = this;
    var selList = e.sl;
    that.setData({ selList: selList });
  },
  confirmOrder: function (e) {
    wx.showLoading();
    var that = this;
    var said = 0;
    if (this.data.showAdress){
      if (that.data.curAddressData) {
        said = that.data.curAddressData.SAId;
      } else {
        said = 0;
      }
    }else{
       said = 0;
    }
    
   
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,
      SelList: that.data.selList
    }
    //初始化优惠券
    wx.showLoading();
    wx.request({
      url: app.globalData.host + '/api/order/GetValidCouponList',
      data: {
        selList: that.data.selList,
        uid: app.globalData.userInfo.Uid
      }, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.Code != 0) {
          return;
        }
        if (res.data.Data.length>0){
          that.setData({
            allCoupon: res.data.Data,
            curCoupon: res.data.Data[0]
          });
        }
      }
    })
    //初始化订单
    wx.request({
      url: app.globalData.host + '/api/order/confirmorderv2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        console.log(res)
        wx.hideLoading();
        if (res.data.Code != 0 & that.data.hasPay == false) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        }
        that.setData({
          hasPay: true
        });
        //订单确认成功
        var confirm = that.processImageHost(res.data.Data);
        var curCoupon = that.data.curCoupon;
        if (curCoupon){
          var payMoney = confirm.AllOrderAmount - curCoupon.Money;
          payMoney = payMoney.toFixed(2);
          that.setData({
            payMoney: payMoney
          });
        }
        that.setData({
          confirmOrder: confirm,
        });
      }
    })
  },
  processImageHost: function (cart) {
    if (cart.StoreOrderList.length > 0) {
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartProductList.length; i++) {
        //主图
        cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].OrderProductInfo.ShowImg;
        if (cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length > 0) {
          for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList.length; j++) {
            //赠品图片
            cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartProductList[i].GiftList[j].ShowImg;
          }
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartFullCutList[i].FullCutCartProductList[j].OrderProductInfo.ShowImg;
        }
      }
      for (var i = 0; i < cart.StoreOrderList[0].StoreCartInfo.CartSuitList.length; i++) {
        for (var j = 0; j < cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList.length; j++) {
          cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg = app.globalData.image190_190host + cart.StoreOrderList[0].StoreCartInfo.CartSuitList[i].CartProductList[j].OrderProductInfo.ShowImg;
        }
      }
    }
    return cart;

  },

  createOrder: function (e) {
    var that = this;
    if (that.data.curCoupon) {
      var curCoupon = that.data.curCoupon.Money//优惠券
    } else {
      var curCoupon = 0
    }
    var PayCreditPrice = that.data.confirmOrder.PayCreditPrice//积分价格
    if (e.detail.value.PayCredits) {
      var PayCredits = e.detail.value.PayCredits / 100 * PayCreditPrice//积分金额
    } else {
      var PayCredits = 0
    }
    var AllOrderAmount = that.data.confirmOrder.AllOrderAmount//订单总额
    var AllFullCut = that.data.confirmOrder.AllFullCut//满减
    var cashNew = that.data.cash//余额
    if (that.data.choosecash == 2) {//判断是否选中
      if (that.data.cash > AllOrderAmount) {//判断是否大于商品总额
        cashNew = AllOrderAmount
      }
    }
    var countMoney = parseFloat(curCoupon) + parseFloat(AllFullCut) + parseFloat(PayCredits)  + parseFloat(cashNew)//优惠总和
    var uid = app.globalData.userInfo.Uid // 用户登录 uid
    if (!uid) {
      wx.showModal({
        title: '提示',
        content: '获取用户信息失败',
        showCancel: false
      })
      return;
    }
    var couponIdList = '';
    if (that.data.curCoupon) {
      couponIdList = that.data.curCoupon.CouponId;
    }
    var remark = e.detail.value.remark; // 备注信息
    var remark2 ="\t" + "联系人：" + e.detail.value.remark2; // 联系人
    var remark3 = "\t" +"手机号："  + e.detail.value.remark3; // 手机号
    if(this.data.showAdress){//非自提
        remark2 = "";
        remark3 = "";
    }else{//自提
      if (e.detail.value.remark2 == "") {
        wx.showModal({
          title: '提示',
          content: '自提请填写联系人',
          showCancel: false
        });
        return;
      }
      if (e.detail.value.remark3 == "") {
        wx.showModal({
          title: '提示',
          content: '自提请填写联系电话',
          showCancel: false
        });
        return;
      }
      if (!util.vailPhone(e.detail.value.remark3)){
        wx.showModal({
          title: '提示',
          content: '请输入正确的手机号！',
          showCancel: false
        });
        return;
      }
    }
    var CreditCount = e.detail.value.PayCredits; // 积分
    if (CreditCount == "" || CreditCount == null) {
      CreditCount = 0
    }
    if (that.data.choosecash == 2) {
      if (that.data.confirmOrder.AllProductAmount < that.data.cash) {
        var payCash = that.data.confirmOrder.AllProductAmount
      } else {
        var payCash = that.data.cash
      }

    } else {
      payCash = 0
    }
    var said = 0;
    if (this.data.showAdress) {//自提地址判断 非自提
      if (that.data.curAddressData == null || !that.data.curAddressData.SAId) {
        wx.showModal({
          title: '提示',
          content: '请填写地址信息',
          showCancel: false
        });
        return;
      }else{
        said = that.data.curAddressData.SAId;
      }
    } else {
      said = 0;
    }
    var postData = {
      Uid: app.globalData.userInfo.Uid,
      SaId: said,//配送地址id
      SelList: that.data.selList,//选中的购物车项键列表
      PayCreditCount: CreditCount,//支付积分
      PayCash: payCash,//余额支付
      CouponIdList: couponIdList,//客户已经激活的优惠劵
      CouponSNList: '',//客户还未激活的优惠劵
      FullCut: that.data.confirmOrder.AllFullCut,//验证满减金额
      BuyerRemark: remark + remark2 + remark3 //备注
    }
    wx.showLoading({
      title: '提交中',
    })
    wx.request({
      url: app.globalData.host + '/api/order/SubmitOrderV2',
      method: 'POST',
      data: postData, // 设置请求的 参数
      success: (res) => {
        console.log(res)
        wx.hideLoading();
        if (res.data.Code != 0) {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
          return;
        } else {
          if (countMoney >= AllOrderAmount) {//判断优惠金额是否大于或等于订单金额
            wx.redirectTo({
              url: '/pages/order-list/index',
            })
          } else {
            // 下单成功，跳转到支付界面
            var oid = res.data.Data;
            wxpay.wxpay(app, oid, "/pages/order-list/index");
            return;
          }
        }
      }
    })
  },
  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetDefaultShipAddress',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: (res) => {
        if (res.data.Code == 0) {
          that.setData({
            curAddressData: res.data.Data
          });
        }
        this.confirmOrder();
      }
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index?said=0"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  selectCoupon: function () {
    wx.navigateTo({
      url: "/pages/member/coupon/index?st=1&sl=" + this.data.selList
    })
  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    var that = this;
    wx.showLoading({
      title: '正在刷新',
      success: function () {
        that.confirmOrder()
      }
    })

    wx.stopPullDownRefresh();
  }
})
